/* ================
Fonctions utiles
================ */
var IE = (navigator.appName.toLowerCase() != "netscape");
// for compatibility only
function var_dump(tab){return true;}
function inArray(v,a){return a.indexOf(v);}
Array.prototype.positionOf = function(v){return this.indexOf(v);}
String.prototype.trim = function(){return this.strip();}

function deselectTous()
{
    itemsSelected(true);
    tagsSelected(true);
}

function getPageSize()
{
    // thanks to Cody Lindley
    var de = document.documentElement;
    var w  = window.innerWidth  || self.innerWidth  || (de&&de.clientWidth)  || document.body.clientWidth;
    var h  = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;

    arrayPageSize = new Array(w,h);
    return arrayPageSize;
}

function getImageSize(imageWidth, imageHeight)
{
    // thanks to Christian Montoya
    var pagesize = getPageSize();
    //var x = pagesize[0] - 150;
    var y = pagesize[1] - 120;
    var x = 640;
    //var y = 480;

    if (imageWidth > x)
    {
        imageHeight = imageHeight * (x / imageWidth); 
        imageWidth  = x; 
        if (imageHeight > y)
        { 
            imageWidth  = imageWidth * (y / imageHeight); 
            imageHeight = y; 
        }
    } 
    else if (imageHeight > y)
    { 
        imageWidth  = imageWidth * (y / imageHeight); 
        imageHeight = y; 
        if (imageWidth > x)
        { 
            imageHeight = imageHeight * (x / imageWidth); 
            imageWidth  = x;
        }
    }

    arrayImageSize = new Array(imageWidth,imageHeight);
    return arrayImageSize;
}

var errFunc = function(t) 
{
    alert('Error ' + t.status + ' -- ' + t.statusText);
}

var handlerFuncBase = function(t)
{
    var r = t.responseText.split(':');
    if(r[0] != 'ok') alert(r[1]);
}
/* =======================
Captures des évenements
======================= */

function supprSelection()
{
    var supprItem = itemsSelected();
    if(supprItem.length > 0 && confirm('Êtes-vous sûr de vouloir supprimer les items sélectionnés ?'))
    {
        var lepostBody = 'ACTION_ITEM=DEL'
        +'&ID_ITEM[]='+supprItem.join('&ID_ITEM[]=');

        var handlerFunc = function(t)
        {
            var r = t.responseText.split(':');
            if(r[0] != 'ok')
            {
                alert(r[1]);
            }
            else
            {
                itemsAction('supprimer', supprItem);
            }
        }

        var errFunc = function(t)
        {
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }

        debLoad();
        new Ajax.Request('index.php?page=ajaxItem', {method:'post', postBody:lepostBody, onSuccess:handlerFunc, onFailure:errFunc, onComplete:finLoad}); 
    }

    var supprTag = tagsSelected();
    if(supprTag.length > 0 && confirm('Êtes-vous sûr de vouloir supprimer les tags sélectionnés ?'))
    {
        tagsAction('supprimer', supprTag);
    }
}

document.onkeyup = function(e)
{
    var touche = window.event ? window.event.keyCode : e.which;
    if(touche == 46)
    {
        supprSelection();
    }
}

function debLoad()
{
    Element.show('loading');
}

function finLoad()
{
    Element.hide('loading');
}

var idActif;
window.onload = function()
{
    cacherPages = function(etat)
    {
        if(!IE) return; // Contre un bug IE qui affiche les boite déroulante par dessus les divs, Merci a darty.com pour l'idée de la solution
        if(etat) Element.hide('changerDePage');
        else     Element.show('changerDePage');
    }

    var cacherTous = function()
    {
        Element.hide('popin');
        Element.hide('popinBackground');
        Element.hide('dial');
        Element.hide('identification');
        Element.hide('upload');
        Element.hide('uploadChoix');
        Element.hide('uploadLocal');
        Element.hide('uploadLien');
        Element.hide('deconnexion');
        Element.hide('recherche');
	Element.hide('moddroits');
        Element.hide('aide');
        cacherPages(false);
        cacherTous2();
    }

    Event.observe('popinBackground', 'click', cacherTous);
    Event.observe('popinClose', 'click', cacherTous);
    Event.observe('actionSuppr', 'click', supprSelection);
    Event.observe('actionViderSel', 'click', deselectTous);

    Event.observe('popinNext', 'click', function(e)
    {
        var pos = inArray(idActif, idsItem);
        pos++;
        if(pos >= idsItem.length) pos = 0;
        if(pos < 0 ) pos = idsItem.length - 1;
        idActif = idsItem[pos];

        cacherTous();
        items[idsItem[pos]].voirDetail();
        Event.stop(e);    
        scroll(0,0);
    });

    Event.observe('popinPrev', 'click', function(e)
    {
        var pos = inArray(idActif, idsItem);
        pos--;
        if(pos >= idsItem.length) pos = 0;
        if(pos < 0 ) pos = idsItem.length - 1;
        idActif = idsItem[pos];

        cacherTous();
        items[idsItem[pos]].voirDetail();
        Event.stop(e);    
        scroll(0,0);
    });

    Event.observe('modeTag', 'click', function(e)
    {
        actionLienTagEx = !actionLienTagEx;
        if(!actionLienTagEx){
            $('modeTag').style.color = 'black';
        }
        else{
            $('modeTag').style.color = 'white';
        }
        Event.stop(e);
    });

    Event.observe('actionLogin', 'click', function(e)
    {
        cacherTous();
        cacherPages(true);
        Element.show('identification');
        Element.show('popinBackground');
        Element.show('dial');
        $('i1').focus();    
        scroll(0,0);
    });

    Event.observe('actionRecherche', 'click', function(e)
    {
        cacherTous();
        cacherPages(true);
        Element.show('recherche');
        Element.show('popinBackground');
        Element.show('dial');
        $('r1').focus();    
        scroll(0,0);
    });

    Event.observe('actionAddItem', 'click', function(e)
    {
        cacherTous();
        cacherPages(true);
        Element.show('uploadChoix');
        Element.show('upload');
        Element.show('popinBackground');
        Element.show('dial');
        $('upLocal').focus();    
        scroll(0,0);
    });

    Event.observe('actionLogout', 'click', function(e)
    {
        cacherTous();
        cacherPages(true);
        Element.show('deconnexion');
        Element.show('popinBackground');
        Element.show('dial');
        $('decoBouton').focus();    
        scroll(0,0);
    });

    Event.observe('actionAide', 'click', function(e)
    {
        cacherTous();
        cacherPages(true);
        Element.show('aide');
        Element.show('popinBackground');
        Element.show('dial');    
        scroll(0,0);
    });    

    Event.observe('actionModDroitsSel', 'click', function(e)
    {
        cacherTous();
        cacherPages(true);
        Element.show('moddroits');
        Element.show('popinBackground');
        Element.show('dial');    
        scroll(0,0);
    });

    var elementList = document.getElementsByClassName("bAnnuler");
    var i = 0;
    for(i = 0; i < elementList.length; i++)
    {
        Event.observe(elementList[i], 'click', function(e)
        {
            cacherTous();
        });
    }

    Event.observe('upLocal', 'click', function(e)
    {
        Element.hide('uploadChoix');
        Element.show('uploadLocal');
        $('u1').focus();    
        scroll(0,0);
    });

    Event.observe('upDistant', 'click', function(e)
    {
        Element.hide('uploadChoix');
        Element.show('uploadLien');
        $('u2').focus();    
        scroll(0,0);
    });
    
    
    
    function pprinc()
    {
        window.location = 'index.php';
    }

    Event.observe('logo', 'click', pprinc);
    Event.observe('annulRecherche', 'click', pprinc);

    var lesTagsCachesAdd = true;
    Event.observe('ajouterTagAction', 'click', function(e)
    {
        if(lesTagsCachesAdd) Element.show('ajouterTag');
        else                 Element.hide('ajouterTag');
        lesTagsCachesAdd = !lesTagsCachesAdd;
        $('nom_tag').focus();
        Event.stop(e);
    });

    Event.observe('addItemDistantPlus', 'click', function(e)
    {    
        new Insertion.Before('addItemDistantPlus', '<fieldset><legend>'+lang_nvlitem+'</legend><label for="a'+(uniqueId)+'">'+lang_entrezaddlien+'<br /><input id="a'+(uniqueId)+'" name="FICHIERL['+nbFichierAjout+']" type="text" /></label><h2>'+lang_tags+'</h2>'+formTag.replace(/%NUM%/g,nbFichierAjout)+'<br /><h2>'+lang_droits+'</h2><input type="radio" name="DROITS_ITEM['+nbFichierAjout+']" value="0" checked="checked" /> '+lang_prive+' <input type="radio" name="DROITS_ITEM['+nbFichierAjout+']" value="1" /> '+lang_pub+'</fieldset>');
        uniqueId++;
        nbFichierAjout++;
        Event.stop(e);
    });

    function validerAjoutTag(e)
    {
        var lienTag  = params.replace(/&amp;/g, '&');
        lienTag      = lienTag.replace(/page=js&/,'');
        var lienTagP = lienTag.replace(/tags=/,'tags='+$F('nom_tag')+',');
        lienTag     += '&pageNb=1&tags='+$F('nom_tag');

        var ttmp = new Tag('tag'+(uniqueId++), $F('nom_tag'), 1, lienTag, 0, 0, lienTagP);
        ttmp.ajaxSave(); //et affiche
        Element.hide('ajouterTag');
        $('nom_tag').value = '';
        Event.stop(e);
    }

    Event.observe('add_tag_form', 'submit', validerAjoutTag);
    Event.observe('add_tag', 'click', validerAjoutTag);

    Event.observe('changerDePage', 'change', function(e)
    {
       window.location = '?'+$F('changerDePage');
    });

    if(/PLUGIN=com/.test(document.location))
    {
        cacherTous();
        cacherPages(true);
        Element.show('ComUNIID');
        Element.show('popinBackground');
        Element.show('dial');     
        scroll(0,0);
    }

    load2();
    finLoad();
    
}

var cacherPages;
window.onunload = function() 
{

}

function createCookie(name,value,days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

var actionLienTagEx = true;
var nbFichierAjout = 1;
var uniqueId       = 10;
